#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<windows.h>
/*最大用户数量*/
#define MAX_USERS 20
 /*用户结构*/
typedef struct User {
	char username[20];
	char password[20];
}User;
User users[MAX_USERS];

/*注册函数*/
void registerUser(User users[MAX_USERS]) {
    if (MAX_USERS <= 0) {
        printf("注册失败：用户数量已达上限\n");
        return;
    }
    int i = 0;

    printf("请输入用户名：");
    char newUsername[20];
    scanf("%s", newUsername);

    /*检查用户名是否已存在*/
    for (i = 0; i < MAX_USERS; ++i) {
        if (strcmp(users[i].username, newUsername) == 0) {
            printf("注册失败：用户名已存在\n");
            return;
        }
    }

    printf("输入密码:");
    char newPassword[20];
    scanf("%s", newPassword);

    /*将新用户添加到数组*/
    for (i = 0; i < MAX_USERS; ++i) {
        if (users[i].username) {
            strcpy(users[i].username, newUsername);
            strcpy(users[i].password, newPassword);
            break;
        }
    }
    FILE* pf = fopen("user.txt", "a");
    fprintf(pf, "%s %s\n", users[i].username, users[i].password);
    fclose(pf);
    pf = NULL;
    printf("注册成功\n");
}
/*登录系统*/
void loginUser(User users[MAX_USERS]) {
    printf("请输入用户名:");
    char inputUsername[20];
    scanf("%s", inputUsername);

    printf("请输入密码:");
    char inputPassword[20];
    scanf("%s", inputPassword);
    /*验证用户身份*/
    for (int i = 0; i < MAX_USERS; ++i) {
        if (strcmp(users[i].username, inputUsername) == 0 && strcmp(users[i].password, inputPassword) == 0) {
            printf("登录成功\n");
            return;
        }
    }
    printf("登录失败：用户名或密码错误\n");
}



void menu()
{
	printf("||== 欢迎使用排班系统  ==||\n");
	printf("||== 输入1进行用户注册 ==||\n");
	printf("||== 输入2进行用户登录 ==||\n");
	printf("||== 输入0退出程序     ==||\n");
}

int main()
{
	int cho = 0;
	FILE* pf = fopen("user.txt", "r");
	char op;
	int i = 0;
	while (fscanf(pf, "%s %s", &users[i].username, &users[i].password) != EOF)
	{
		i++;
	}
	fclose(pf);
	pf = NULL;
	do
	{
		menu();
		printf("请选择：");
		scanf("%d", &cho);
		switch (cho)
		{
		case 1:registerUser(users);continue;
		case 2:loginUser(users);continue;
		case 0:break;
		default:printf("输入错误，请重新输入：");continue;
		}
	} while (cho);
	return 0;
}